package com.tiantian.quanminxiu.dialog;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.shenglian.utils.utils.CommonUtils;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.api.SocketUtils;
import com.tiantian.quanminxiu.event.LiveRoomEvent;
import com.tiantian.quanminxiu.event.SocketGiftEvent;
import com.tiantian.quanminxiu.model.GiftModel;
import com.tiantian.quanminxiu.module.PageRecyelerView.PageIndicatorView;
import com.tiantian.quanminxiu.module.PageRecyelerView.PageRecyclerView;
import com.tiantian.quanminxiu.presenter.DialogGiftListPresent;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.EventBusUtils;
import com.tiantian.quanminxiu.utils.UserData;
import com.tiantian.quanminxiu.view.DialogGiftListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action1;

public class Dialog_GiftList implements DialogGiftListView{

    //region 初始化数据
    private static Dialog_GiftList dialog_giftList;
    private PopupWindow popupWindow;
    private Activity activity;
    private int anchor_id;
    private String anchor_name;

    private DialogGiftListPresent dialogGiftListPresent;
    private int GiftSelectPosition,PackageSelectPosition;

    private LinearLayout linGiftList,linGiftCount,linChangeGift,linChangePackage,linVpGiftList,linVpPackageList,linSubGiftCount,linRecharge;
    private LinearLayout linGiftCount1,linGiftCount10,linGiftCount66,linGiftCount99,linGiftCount188,
            linGiftCount520,linGiftCount1314,linGiftCount3344,linGiftCount6666,linGiftCount9999;
    private TextView txtOpenGuard,txtUserMoney,txtSubPresent,txtGiftCount,txtGiftCountCancel,txtChangeGift,txtChangePackage;
    private View vChangeGift,vChangePackage,vMain;

    private PageRecyclerView rvGiftList,rvPackageList;
    private PageIndicatorView linPointsGift,linPointsPackage;

    private List<GiftModel> giftList,PackageList;


    private int GiftCount = 1;
    private int GiftId;
    private int PackageId,PackageNum;
    //endregion

    //region onCreate
    private Dialog_GiftList(Activity activity,int anchor_id,String anchor_name) {
        this.activity = activity;
        this.anchor_id = anchor_id;
        this.anchor_name = anchor_name;
        View view = View.inflate(activity,R.layout.dialog_giftlist,null);
        initPopupWindow(view);
        InitView(view);

        EventBusUtils.getInstance().register(this);
        dialogGiftListPresent = new DialogGiftListPresent();
        dialogGiftListPresent.attachView(this);
        dialogGiftListPresent.initGiftList();
    }
    //endregion

   private void getGiftData(){
       txtUserMoney.setText("金币：" + UserData.Base.Coin);
       txtGiftCount.setText(GiftCount + "");

       rvGiftList.setIndicator(linPointsGift);
       rvPackageList.setIndicator(linPointsPackage);
       rvGiftList.setAdapter(rvGiftList.new PageAdapter(giftList, new PageRecyclerView.CallBack() {
           @Override
           public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
               return new MyViewHolder(LayoutInflater.from(
                       activity).inflate(R.layout.dialog_giftlist_item, parent,
                       false));
           }

           @Override
           public void onBindViewHolder(RecyclerView.ViewHolder viewholder, int position) {
               MyViewHolder holder = (MyViewHolder) viewholder;
               GiftModel giftModel = giftList.get(position);
               holder.vMain.setBackgroundResource(0);
               if (giftModel.getSelect() != 0) {
                   holder.vMain.setBackgroundResource(R.drawable.icon_gift_selected);
               }
               holder.txtGiftName.setText(giftModel.getGiftName());
               holder.txtGiftPrice1.setText(giftModel.getPrice() < 0 ? "" : (giftModel.getPrice() + "币"));
               APPUtils.displayImage(APPUtils.createGiftImg(giftModel.getGiftID()), holder.imgGiftPic, true);
           }

           @Override
           public void onItemClickListener(View view, int position) {
               GiftId = giftList.get(position).getGiftID();
               rvGiftList.getAdapter().notifyItemChanged(GiftSelectPosition);
               giftList.get(GiftSelectPosition).setSelect(0);
               giftList.get(position).setSelect(1);
               rvGiftList.getAdapter().notifyItemChanged(position);
               GiftSelectPosition = position;
           }

           @Override
           public void onItemLongClickListener(View view, int position) {

           }
       }));
       rvPackageList.setAdapter(rvPackageList.new PageAdapter(PackageList, new PageRecyclerView.CallBack() {
           @Override
           public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
               return new MyViewHolder(LayoutInflater.from(
                       activity).inflate(R.layout.dialog_giftlist_item, parent,
                       false));
           }

           @Override
           public void onBindViewHolder(RecyclerView.ViewHolder viewholder, int position) {
               MyViewHolder holder = (MyViewHolder) viewholder;
               GiftModel giftModel = PackageList.get(position);
               holder.txtGiftName.setText(giftModel.getGiftName());
               holder.vMain.setBackgroundResource(0);
               if (giftModel.getSelect() != 0) {
                   holder.vMain.setBackgroundResource(R.drawable.icon_gift_selected);
               }
               holder.txtGiftPrice1.setText(giftModel.getNum() < 0 ? "" : (giftModel.getNum() + "个"));
               APPUtils.displayImage(APPUtils.createGiftImg(giftModel.getGiftID()), holder.imgGiftPic, true);
           }

           @Override
           public void onItemClickListener(View view, int position) {
               PackageId = PackageList.get(position).getGiftID();
               PackageNum = PackageList.get(position).getNum();
               rvPackageList.getAdapter().notifyItemChanged(PackageSelectPosition);
               PackageList.get(PackageSelectPosition).setSelect(0);
               PackageList.get(position).setSelect(1);
               rvPackageList.getAdapter().notifyItemChanged(position);
               PackageSelectPosition = position;
           }

           @Override
           public void onItemLongClickListener(View view, int position) {

           }
       }));
    }

    public static Dialog_GiftList getInstance(Activity activity,int anchor_id,String anchor_name){
        if(dialog_giftList==null){
            dialog_giftList = new Dialog_GiftList(activity,anchor_id,anchor_name);
        }
        return dialog_giftList;
    }

    //region 关闭窗口 closeWindow
    public void closeWindow(){
        EventBusUtils.getInstance().unregister(this);
        popupWindow.dismiss();
        dialogGiftListPresent.detachView();
        dialog_giftList = null;
    }
    //endregion

    //region 显示窗口 show(View view)
    public void show(View view){
        if (null != popupWindow) {
            popupWindow.showAtLocation(view, Gravity.BOTTOM
                    | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    }
    //endregion

    //region 是否展示 isShow
    public boolean isShow(){
        if(popupWindow==null){
            return false;
        }
        return popupWindow.isShowing();
    }
    //endregion

    //region 初始化popwindow initPopupWindow(View view)
    public void initPopupWindow(View view){
        popupWindow = new PopupWindow();
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ActionBar.LayoutParams.FILL_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        popupWindow.setHeight(ActionBar.LayoutParams.FILL_PARENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.AnimBottom);
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(true);

        view.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        view.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
                if (arg1 == KeyEvent.KEYCODE_BACK) {
                    if (popupWindow != null) {
                        closeWindow();
                    }
                }
                return false;
            }
        });
    }
    //endregion

    //region InitView(View view)
    public void InitView(View view) {
        vChangeGift = view.findViewById(R.id.vChangeGift);
        vChangePackage = view.findViewById(R.id.vChangePackage);
        vMain = view.findViewById(R.id.vMain);

        rvGiftList = (PageRecyclerView) view.findViewById(R.id.rvGiftList);
        rvPackageList = (PageRecyclerView) view.findViewById(R.id.rvPackageList);

        linGiftList = (LinearLayout) view.findViewById(R.id.linGiftList);
        linGiftCount = (LinearLayout) view.findViewById(R.id.linGiftCount);
        linChangeGift = (LinearLayout) view.findViewById(R.id.linChangeGift);
        linChangePackage = (LinearLayout) view.findViewById(R.id.linChangePackage);
        linSubGiftCount = (LinearLayout) view.findViewById(R.id.linSubGiftCount);
        linRecharge = (LinearLayout) view.findViewById(R.id.linRecharge);
        linPointsGift = (PageIndicatorView) view.findViewById(R.id.linPointsGift);
        linPointsPackage = (PageIndicatorView) view.findViewById(R.id.linPointsPackage);
        linVpGiftList = (LinearLayout) view.findViewById(R.id.linVpGiftList);
        linVpPackageList = (LinearLayout) view.findViewById(R.id.linVpPackageList);

        linGiftCount1 = (LinearLayout) view.findViewById(R.id.linGiftCount1);
        linGiftCount10 = (LinearLayout) view.findViewById(R.id.linGiftCount10);
        linGiftCount66 = (LinearLayout) view.findViewById(R.id.linGiftCount66);
        linGiftCount99 = (LinearLayout) view.findViewById(R.id.linGiftCount99);
        linGiftCount188 = (LinearLayout) view.findViewById(R.id.linGiftCount188);
        linGiftCount520 = (LinearLayout) view.findViewById(R.id.linGiftCount520);
        linGiftCount1314 = (LinearLayout) view.findViewById(R.id.linGiftCount1314);
        linGiftCount3344 = (LinearLayout) view.findViewById(R.id.linGiftCount3344);
        linGiftCount6666 = (LinearLayout) view.findViewById(R.id.linGiftCount6666);
        linGiftCount9999 = (LinearLayout) view.findViewById(R.id.linGiftCount9999);

        txtOpenGuard = (TextView) view.findViewById(R.id.txtOpenGuard);
        txtUserMoney = (TextView) view.findViewById(R.id.txtUserMoney);
        txtSubPresent = (TextView) view.findViewById(R.id.txtSubPresent);
        txtGiftCount = (TextView) view.findViewById(R.id.txtGiftCount);
        txtGiftCountCancel = (TextView) view.findViewById(R.id.txtGiftCountCancel);
        txtChangeGift = (TextView) view.findViewById(R.id.txtChangeGift);
        txtChangePackage = (TextView) view.findViewById(R.id.txtChangePackage);
        txtOpenGuard.setVisibility(View.VISIBLE);
        if(anchor_id<0){
            txtOpenGuard.setVisibility(View.GONE);
        }

        RxView.clicks(vMain).map(View->vMain).subscribe(OC_Button);
        RxView.clicks(linChangeGift).map(View->linChangeGift).subscribe(OC_Button);
        RxView.clicks(linChangePackage).map(View->linChangePackage).subscribe(OC_Button);
        RxView.clicks(linSubGiftCount).map(View->linSubGiftCount).subscribe(OC_Button);
        RxView.clicks(txtGiftCountCancel).map(View->txtGiftCountCancel).subscribe(OC_Button);
        RxView.clicks(linRecharge).map(View->linRecharge).subscribe(OC_Button);
        RxView.clicks(txtSubPresent).map(View->txtSubPresent).subscribe(OC_Button);
        RxView.clicks(txtOpenGuard).map(View->txtOpenGuard).subscribe(OC_Button);

        RxView.clicks(linGiftCount1).map(View->linGiftCount1).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount10).map(View->linGiftCount10).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount66).map(View->linGiftCount66).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount99).map(View->linGiftCount99).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount188).map(View->linGiftCount188).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount520).map(View->linGiftCount520).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount1314).map(View->linGiftCount1314).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount3344).map(View->linGiftCount3344).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount6666).map(View->linGiftCount6666).subscribe(OC_GiftCount);
        RxView.clicks(linGiftCount9999).map(View->linGiftCount9999).subscribe(OC_GiftCount);
    }
    //endregion

    //region 得到礼物列表 getGiftList
    @Override
    public void getGiftList(JSONArray giftArray,JSONArray packageArray) {
        giftList = new ArrayList<GiftModel>();
        for (int i=0;i<giftArray.length();i++){
            GiftModel giftModel = new GiftModel();
            JSONObject object = giftArray.optJSONObject(i);
            if(i==0){
                giftModel.setSelect(1);
                GiftId = object.optInt("id");
            }
            giftModel.setGiftName(object.optString("Name"));
            giftModel.setGiftID(object.optInt("id"));
            giftModel.setPrice(object.optInt("Price"));
            giftList.add(giftModel);
        }

        PackageList = new ArrayList<GiftModel>();
        for (int i=0;packageArray!=null&&i<packageArray.length();i++){
            GiftModel giftModel = new GiftModel();
            JSONObject object = packageArray.optJSONObject(i);
            JSONObject Item_Info = object.optJSONObject("Item_Info");
            giftModel.setGiftName(Item_Info.optString("Name"));
            giftModel.setGiftID(Item_Info.optInt("id"));
            giftModel.setNum(object.optInt("Num"));
            PackageList.add(giftModel);
        }
        getGiftData();
    }
    //endregion

    //region 得到包裹列表 getGiftList
    @Override
    public void getPackList(JSONArray packageArray) {

    }
    //endregion

    //region 发送礼物 PresentGift
    //purchasemode purchasemode=1为礼物 purchasemode=2位包裹
    @Override
    public void PresentGift(int gift, int num,int purchasemode) {
        Loading_Open();
        SocketUtils.getInstance().sendMessage("Gift", gift, num,anchor_id,purchasemode);
    }
    //endregion

    //region 接受socket礼物消息 receiveGiftSocket(SocketGiftEvent event)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveGiftSocket(SocketGiftEvent event){
        if(event.getJsonObject() == null) {
            return;
        }
        JSONObject jsonObject = event.getJsonObject();
        switch (event.getSocketTyep()) {
            case SocketUtils.GIFTLINSENER:
                //region 我发送礼物监听 GIFTLINSENER
                Loading_Close();
                if (jsonObject.optString("flag").equals("0")) {
                    try {
                        jsonObject = new JSONObject(jsonObject.optString("Data"));
                        JSONObject GiftInfo = jsonObject.optJSONObject("GiftInfo");
                        JSONObject giftRoomUserInfo = jsonObject.optJSONObject("RoomUserInfo");
                        UserData.Base.Coin = giftRoomUserInfo.optInt("Coin");
                        UserData.Base.Beans = giftRoomUserInfo.optInt("Beans");
                        UserData.Reload.Fragment_Mine = true;
                        UserData.Base.UserPackage = jsonObject.optJSONArray("UserPackage");
                        if(linVpGiftList.getVisibility()==View.VISIBLE){
                            txtUserMoney.setText("金币：" + UserData.Base.Coin);
                        }else{
                            for (int i=0;i<PackageList.size();i++){
                                GiftModel giftModel = PackageList.get(i);
                                if(giftModel.getGiftID()==PackageId){
                                    giftModel.setNum(giftModel.getNum()-1);
                                    PackageNum = giftModel.getNum();
                                    rvPackageList.getAdapter().notifyItemChanged(PackageSelectPosition);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else if(jsonObject.optString("flag").equals("-2")){
                    CommonUtils.showToask(activity, jsonObject.optString("message"));
                    Recharge_To();
                } else {
                    CommonUtils.showToask(activity, jsonObject.optString("message"));
                }
                //endregion
                break;
        }
    }
    //endregion

    //region 接受socket聊天消息 receiveMsgSocket(SocketMsgEvent event)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveLiveMsg(LiveRoomEvent event) {
        if(event.getType()==null){
            return;
        }
        switch (event.getType()){
            case "RechargeSuccess":
                txtUserMoney.setText("金币：" + UserData.Base.Coin);
                break;
        }
    }
    //endregion

    //region 充值页面 Recharge_To
    @Override
    public void Recharge_To() {
        APPUtils.Recharge_TO(activity,true);
    }
    //endregion

    //region 开通守护 OpenGuard_To
    @Override
    public void OpenGuard_To() {
        APPUtils.Dialog_OpenGuard_To(activity,anchor_id+"",anchor_name);
    }
    //endregion

    //region getContext
    @Override
    public Context getContext() {
        return activity;
    }

    @Override
    public void Loading_Open() {

    }

    @Override
    public void Loading_Open(boolean flag) {

    }

    @Override
    public void Loading_Close() {

    }
    //endregion

    //region 关闭窗口 OC_Button
    private Action1<View> OC_Button = v->{
        switch (v.getId()){
            case R.id.vMain:
                closeWindow();
                break;
            case R.id.linRecharge:
                Recharge_To();
                break;
            case R.id.txtSubPresent:
                if(linVpGiftList.getVisibility()==View.VISIBLE){
                    PresentGift(GiftId, GiftCount,1);
                }else{
                    if(PackageNum<=0){
                        CommonUtils.showToask(activity,"数量不足，请重试..");
                    }else{
                        PresentGift(PackageId,GiftCount,2);
                    }
                }
                break;
            case R.id.txtOpenGuard:
                OpenGuard_To();
                break;
            case R.id.linChangeGift:
                linVpGiftList.setVisibility(View.VISIBLE);
                linVpPackageList.setVisibility(View.GONE);
                txtChangeGift.setTextColor(APPUtils.getResourcesColor(activity, R.color.orange));
                txtChangePackage.setTextColor(APPUtils.getResourcesColor(activity, R.color.wihte));
                vChangeGift.setVisibility(View.VISIBLE);
                vChangePackage.setVisibility(View.INVISIBLE);
                break;
            case R.id.linChangePackage:
                linVpGiftList.setVisibility(View.GONE);
                linVpPackageList.setVisibility(View.VISIBLE);
                txtChangePackage.setTextColor(APPUtils.getResourcesColor(activity, R.color.orange));
                txtChangeGift.setTextColor(APPUtils.getResourcesColor(activity, R.color.wihte));
                vChangePackage.setVisibility(View.VISIBLE);
                vChangeGift.setVisibility(View.INVISIBLE);
                break;
            case R.id.linSubGiftCount:
                linGiftCount.setVisibility(View.VISIBLE);
                linGiftList.setVisibility(View.GONE);
                break;
            case R.id.txtGiftCountCancel:
                linGiftCount.setVisibility(View.GONE);
                linGiftList.setVisibility(View.VISIBLE);
                break;
        }
    };
    //endregion

    //region 礼物数量 OC_GiftCount
    private Action1<View> OC_GiftCount = v->{
        switch (v.getId()){
            case R.id.linGiftCount1:
                GiftCount = 1;
                break;
            case R.id.linGiftCount10:
                GiftCount = 10;
                break;
            case R.id.linGiftCount66:
                GiftCount = 66;
                break;
            case R.id.linGiftCount99:
                GiftCount = 99;
                break;
            case R.id.linGiftCount188:
                GiftCount = 188;
                break;
            case R.id.linGiftCount520:
                GiftCount = 520;
                break;
            case R.id.linGiftCount1314:
                GiftCount = 1314;
                break;
            case R.id.linGiftCount3344:
                GiftCount = 3344;
                break;
            case R.id.linGiftCount6666:
                GiftCount = 6666;
                break;
            case R.id.linGiftCount9999:
                GiftCount = 9999;
                break;
        }
        linGiftCount.setVisibility(View.GONE);
        linGiftList.setVisibility(View.VISIBLE);
        txtGiftCount.setText(GiftCount+"");
    };
    //endregion

    class MyViewHolder extends RecyclerView.ViewHolder
    {
        View relRootGiftCount,vMain;
        ImageView imgGiftPic;
        TextView txtGiftName,txtGiftPrice1,txtGiftCount;

        public MyViewHolder(View view)
        {
            super(view);
            imgGiftPic = (ImageView) view.findViewById(R.id.imgGiftPic);
            relRootGiftCount = view.findViewById(R.id.relRootGiftCount);
            vMain = view.findViewById(R.id.vMain);
            txtGiftName = (TextView) view.findViewById(R.id.txtGiftName);
            txtGiftPrice1 = (TextView) view.findViewById(R.id.txtGiftPrice1);
            txtGiftCount = (TextView) view.findViewById(R.id.txtGiftCount);

        }
    }
}